<!-- 算法配置相关页面 -->
<template>
    <div class="container">
        <div class="header">
        <el-button type="primary" style="width: 10rem;height: 2.7rem" @click="addAlgorithm()">新建算法场景</el-button>  
        <!-- 点击按钮触发的弹窗 -->
        <el-dialog
             v-model="dialogVisibleAdd"
             title="新建算法场景"
             width="500" 
        >
        <div style="width: 100%;display: flex;justify-content: space-evenly;">
            <div style="line-height: 2rem;width: 30%;"><span style="color:red">*</span>算法场景名称：</div>  <el-input v-model="AlgorName" style="width: 70%;height: 2rem;" />
        </div>
      <!-- 算法描述 -->
        <div style="width: 100%;display: flex;justify-content: space-evenly;margin-top: 1rem;">
            <div style="line-height: 2rem;width: 30%;"><span style="color:red">*</span>算法场景描述：</div>  <el-input v-model="AlgorDescription" type="textarea" style="width: 70%;" />
        </div>
        <template #footer>
            <div class="dialog-footer">
            <el-button @click="dialogVisibleAdd = false">取消</el-button>
            <el-button type="primary" @click="upLoadMessage">
                确定
            </el-button>
            </div>
        </template>
        </el-dialog>

        <!-- 修改按钮的弹窗 -->
        <el-dialog
             v-model="dialogVisibleChange"
             title="修改算法场景"
             width="500" 
        >
        <div style="width: 100%;display: flex;justify-content: space-evenly;">
            <div style="line-height: 2rem;width: 30%;">算法场景名称：</div>  <el-input v-model="AlgorNameChange" style="width: 70%;height: 2rem;" />
        </div>
      <!-- 算法描述 -->
        <div style="width: 100%;display: flex;justify-content: space-evenly;margin-top: 1rem;">
            <div style="line-height: 2rem;width: 30%;">算法场景描述：</div>  <el-input v-model="AlgorDescriptionChange" type="textarea" style="width: 70%;" />
        </div>
        <template #footer>
            <div class="dialog-footer">
            <el-button @click="dialogVisibleChange = false">取消</el-button>
            <el-button type="primary" @click="upLoadMessage1">
                确定
            </el-button>
            </div>
        </template>
        </el-dialog>
        </div>
        <div class="main">
          <el-table
  :data="tableData1"
  border
  style="width: 100%; background-color: #fff;"
  highlight-current-row
  :header-cell-style="{ background: '#f5f7fa', color: '#333', fontWeight: 600 }"
>
  <!-- 序号 -->
  <el-table-column label="序号" width="100">
    <template #default="scope">
      {{ (currentPage - 1) * pageSize + scope.$index + 1 }}
    </template>
  </el-table-column>

  <!-- 场景名称 -->
  <el-table-column prop="scenarioName" label="场景名称" width="200" />

  <!-- 场景描述 -->
  <el-table-column prop="scenarioDescription" label="场景描述" width="400" />

  <!-- 演示状态 -->
  <el-table-column prop="status" label="演示状态" width="120">
    <template #default="scope">
      <el-switch
        v-model="scope.row.status"
        :active-value="'S'"
        :inactive-value="'F'"
        @change="handleStatusChange(scope.row)"
      />
    </template>
  </el-table-column>

  <!-- 操作 -->
  <el-table-column prop="apiAddress" label="操作" width="320">
    <template #default="scope">
      <div style="display: flex; flex-wrap: wrap; gap: 6px;">
        <el-button
          link
          type="primary"
          size="small"
          @click="moveToTop(scope.row)"
          style="color: lightsalmon;"
        >
          置顶
        </el-button>
        <el-button
          link
          type="primary"
          size="small"
          :icon="ArrowUp"
          @click="moveUp(scope.row)"
        />
        <el-button
          link
          type="primary"
          size="small"
          :icon="ArrowDown"
          @click="moveDown(scope.row)"
        />
        <el-button
          link
          type="primary"
          size="small"
          @click="moveToBottom(scope.row)"
          style="color: lightseagreen;"
        >
          沉底
        </el-button>
        <el-button
          link
          type="primary"
          size="small"
          @click="changeAlgorithm(scope.row)"
        >
          修改
        </el-button>
        <el-button
          link
          type="primary"
          size="small"
          style="color: red;"
          @click="deleteItem(scope.row)"
        >
          删除
        </el-button>
      </div>
    </template>
  </el-table-column>
</el-table>

   
        </div>
        <Pagination
            :total="totalItems"
            :page-size="pageSize"
            v-model:currentPage="currentPage"
             />
    </div>
</template>

<script lang="ts" setup>
import { useAlgorStore } from '@/stores/algorothm';
import { ref ,computed,nextTick, onMounted} from 'vue';
import { ArrowUp , ArrowDown} from '@element-plus/icons-vue'
import { ElMessage ,ElMessageBox} from 'element-plus'
import request from '@/utils/request';
import Pagination from '../tool/Pagination.vue';

const AlgorName =ref()  //算法名称
const AlgorDescription =ref() //算法描述
const dialogVisibleAdd = ref(false)
const dialogVisibleChange = ref(false)
const algorStore = useAlgorStore()
const currentPage = ref(1); // 当前页
const pageSize = ref(6); // 每页条数



//新增算法场景
const addAlgorithm = () => {
    dialogVisibleAdd.value = true
}

// 上传逻辑
const upLoadMessage = async() => {
  if (!AlgorName.value && !AlgorDescription.value) {
    console.error('存在必填项为空，请重新输入');
    return;
  }
  try {
    const response = request.post('/algorithm/insertAlgorithmScenario', {
      scenarioName:AlgorName.value,
      scenarioDescription:AlgorDescription.value,
    }).then(res=>{
       if(res.data.status == "fail"){
        ElMessage.error(`新增失败，请检查网络后重试`)
       }else {
        ElMessage({
        message: '新增成功',
        type: 'success',
  })
      getAllAlgorithm()
       }  
    });
    dialogVisibleAdd.value = false; // 关闭弹窗
  } catch (error) {
    console.error('Upload failed:', error);
  }
}
// 获取全部的算法并上传到 store
const showAlgorithmScenario = ref();
const notShowAlgorithmScenario = ref();
const AllAlgorithmScenario = ref() 

const getAllAlgorithm = async () => {
  try {
    const res = await request.get('/algorithm/getAllAlgorithmScenario');
    showAlgorithmScenario.value = res.data.show
    notShowAlgorithmScenario.value = res.data.notShow
    AllAlgorithmScenario.value = [...showAlgorithmScenario.value,...notShowAlgorithmScenario.value]
    algorStore.setAlgorData(AllAlgorithmScenario.value);
  } catch (error) {
    console.error('Failed to fetch algorithms:', error);
  }
};

// 删除相关信息
const deleteItem = (item:any) => {
  ElMessageBox.confirm(
    `是否删除场景（${item.scenarioName}），删除后该场景下所有算法将归属未知场景？`,
    '警告',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      request.post('/algorithm/deleteAlgorithmScenario',{
    id:item.id
  }).then((res)=>{
    if(res.data.status == "fail"){
        ElMessage.error(`删除失败，请检查网络后重试`)
       }else {
        ElMessage({
        message: '删除成功',
        type: 'success',
  })
      getAllAlgorithm()
       }  
  })
    })
    .catch(() => {
    })
  
}
//修改状态函数
const handleStatusChange = (item:any) => {  
  ElMessageBox.confirm(
    '是否修下架/上架改算法场景？',
    '警告',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      request.post('/algorithm/updateAlgorithmScenarioStatus',{
      id:item.id,        //  id
      status:item.status,// 新的状态值
  }).then((res)=>{
    if(res.data.status == "fail"){
        ElMessage.error(`修改失败，请检查网络后重试`)
       }else {
        ElMessage({
        message: '状态修改成功',
        type: 'success',
  })
      getAllAlgorithm()
       }  
  })
    })
    .catch(() => {
      getAllAlgorithm()
    })

}
// 修改场景
const changeItem = ref()
const AlgorNameChange =ref()  //算法名称
const AlgorDescriptionChange =ref() //算法描述
const newOrderNumber = ref()
const changeAlgorithm = (item:any) => {
  
    changeItem.value = item
    dialogVisibleChange.value = true
    AlgorNameChange.value = item.scenarioName
    AlgorDescriptionChange.value = item.scenarioDescription
    newOrderNumber.value = item.orderNumber
}
const upLoadMessage1 = async() => {
  if (!AlgorNameChange.value && !AlgorDescriptionChange.value) {
    console.error('存在必填项为空，请重新输入');
    return;
  }
  try {
    const response = request.post('/algorithm/updateAlgorithmScenario', {
      id:changeItem.value.id,
      status:changeItem.value.status,
      primaryScenarioName:changeItem.value.scenarioName,
      scenarioName:AlgorNameChange.value,
      scenarioDescription:AlgorDescriptionChange.value,
      orderNumber:newOrderNumber.value
    }).then(res=>{
       if(res.data.status == "fail"){
        ElMessage.error(`修改失败，请检查当前网路后重试`)
       }else {
        ElMessage({
        message: '修改成功',
        type: 'success',
  })
      getAllAlgorithm()
       }  
    });
    dialogVisibleChange.value = false; // 关闭弹窗
  } catch (error) {
    console.error('Upload failed:', error);
  }
}

const tableData = computed(() => {
  const newShowAlgorithmScenario = showAlgorithmScenario.value?.map((item: any) => ({
    id: item.id,
    scenarioName: item.scenarioName,
    scenarioDescription: item.scenarioDescription,
    status: item.status,
    orderNumber:item.orderNumber,
  })) || [];
  const newNotShowAlgorithmScenario = notShowAlgorithmScenario.value?.map((item: any) => ({
    id: item.id,
    scenarioName: item.scenarioName,
    scenarioDescription: item.scenarioDescription,
    status: item.status,
    orderNumber:item.orderNumber,
  })) || [];



  return [...newShowAlgorithmScenario,...newNotShowAlgorithmScenario]
});

const tableData1 = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return tableData.value?.slice(start, end);
});

const totalItems = computed(() => tableData.value?.length);

// 上移下移，沉底，置顶操作
  // 置顶操作
const  moveToTop =(item:any)=> {
  
  ElMessageBox.confirm(

`是否将场景(${item.scenarioName})置顶？`,
'警告',
{
  confirmButtonText: '确认',
  cancelButtonText: '取消',
  type: 'warning',
}
)
.then(() => {
  request.post('/algorithm/algorithmScenarioMoveToTop',{
    id:item.id
  }).then((res=>{
    if(res.data.status == 'success'){
      getAllAlgorithm()
    }
  }))
})
.catch(() => {
})
    // const index = algorStore.algorithmScenario.findIndex((scenario: any) => scenario.scenario.id === item.id);
    // if (index > 0) {
    //   const [removed] = algorStore.algorithmScenario.splice(index, 1);  // 删除该项
    //   algorStore.algorithmScenario.unshift(removed);  // 将该项添加到数组开头
    // }
  }

  // 沉底操作
 const moveToBottom = (item:any) => {


  ElMessageBox.confirm(

`是否将场景(${item.scenarioName})沉底？`,
'警告',
{
  confirmButtonText: '确认',
  cancelButtonText: '取消',
  type: 'warning',
}
)
.then(() => {
  request.post('/algorithm/algorithmScenarioMoveToBottom',{
    id:item.id
  }).then((res=>{
    if(res.data.status == 'success'){
      getAllAlgorithm()
    }
  }))
})
.catch(() => {
})
    // const index = algorStore.algorithmScenario.findIndex((scenario: any) => scenario.scenario.id === item.id);
    // if (index !== -1 && index < algorStore.algorithmScenario.length - 1) {
    //   const [removed] = algorStore.algorithmScenario.splice(index, 1);  // 删除该项
    //   algorStore.algorithmScenario.push(removed);  // 将该项添加到数组末尾
    // }
  }

  // 上移操作
 const  moveUp = (item:any) => {

  
  ElMessageBox.confirm(

`是否将(${item.scenarioName})场景上移？`,
'警告',
{
  confirmButtonText: '确认',
  cancelButtonText: '取消',
  type: 'warning',
}
)
.then(() => {
  request.post('/algorithm/algorithmScenarioMoveUp',{
    id:item.id
  }).then((res=>{
    if(res.data.status == 'success'){
      getAllAlgorithm()
    }
  }))
})
.catch(() => {
})
    // const index = algorStore.algorithmScenario.findIndex((scenario: any) => scenario.scenario.id === item.id);
    // if (index > 0) {
    //   const temp = algorStore.algorithmScenario[index];
    //   algorStore.algorithmScenario[index] = algorStore.algorithmScenario[index - 1];
    //   algorStore.algorithmScenario[index - 1] = temp;
    // }
  }

  // 下移操作
 const moveDown = (item:any) => {

  
  ElMessageBox.confirm(

`是否将(${item.scenarioName})场景下移？`,
'警告',
{
  confirmButtonText: '确认',
  cancelButtonText: '取消',
  type: 'warning',
}
)
.then(() => {
  request.post('/algorithm/algorithmScenarioMoveDown',{
    id:item.id
  }).then((res=>{
    if(res.data.status == 'success'){
      getAllAlgorithm()
    }
  }))
})
.catch(() => {
})

  }

  onMounted(()=>{
    getAllAlgorithm()
  })

</script>

<style  scoped>
.container {
    width: 100%;
    height: 100%;
}
.header {
    width: 100%;
    height: 14%;
}
.main {
    width: 100%;
    height: 76%;
}
.el-pagination {
  background-color: transparent !important; /* 移除背景颜色 */
  box-shadow: none !important;             /* 去掉可能的阴影 */
}
</style>